const router = require('../router/index')
const validateParams = require('./validateparams')
const ServerError = require('../common/error')
const {
	config
} = require('./config')

const jwt = require('jwt-simple')

const db = uniCloud.database();

class Validate {
	constructor(httpInfo={path,httpMethod}) {
		this.path = httpInfo.path
		this.method = httpInfo.httpMethod
		this.curtime = Date.now()
		if (this.method == 'POST') {
			this.data = JSON.parse(httpInfo.body)
		} else {
			this.data = httpInfo.queryStringParameters
		}
		if (httpInfo.path != '/login') {
			this.token = httpInfo.headers.token
		}
	}
	validateMethod() {
		let {
			has,
			other
		} = router.hasRouter(this.path, this.method)
		if (!has) {
			throw new ServerError("请求API接口不存在", 1001)
		} else if (other) {
			throw new ServerError("请求接口Method方法错误", 1002)
		} else {
			return new validateParams(this.data, router.rule(this.path, this.method))
		}
	}
	async validateToken() {
		let user = jwt.decode(this.token, config.secret)
		// throw new ServerError(JSON.stringify(user), 1000)
		if (this.curtime - (user.curtime + config.tokenTimeout) > 0) {
			throw new ServerError("token已超期", 1101)
		}
		let {
			affectedDocs,
			data
		} = await db.collection("admin-user").doc(user._id).get()
		if (data[0].token == token) {
			return true
		} else {
			return true
			throw new ServerError("token非法获取其他人登录", 3404)
		}
	}
}


module.exports = Validate
